import React, { useState, useEffect } from 'react';
import styles from './index.module.scss';
import WrapperPage from '@/components/WrapperPage';
import CustomIcon from '@/components/CustomIcon';

import { Button, Table, Pagination, Message, Tag, Loading, Dialog } from '@alifd/next';

import { getTunnels, delTunnels } from './services/tunnels';
import handle from '../Devices/components/handle';

const PAGE_SIZE = 10;

const Tunnels = (props) => {
  let [data, onData] = useState([]),
      [currentPage, onCurrentPage] = useState(1),
      [ showLoading, onShowLoading ] = useState(false),
      [sel, onSel] = useState({});
  
  const handleUpdate = () => {
    onShowLoading(true)
    getTunnels().then(res => {
      console.log(res)
      if(res.code == 200) {
        let dataSource = []
        res.msg.forEach(item => {
          dataSource.push({
            id: item._id,
            interfaceA: item.interfaceA,
            interfaceB: item.interfaceB,
            deviceA: item.deviceA.name,
            deviceB: item.deviceB.name,
            pathlabel: !!item.pathLabel ? item.pathLabel : 'None',
            rtt: !!item.tunnelStatusA.rtt ? item.tunnelStatusA.rtt : 'None',
            drop_rate: !!item.tunnelStatusA.drop_rate ? Math.max(Number(item.tunnelStatusA.drop_rate),Number(item.tunnelStatusB.drop_rate)).toFixed(2) : 'None',
            status: !!item.tunnelStatusA.status ? ( item.tunnelStatusA.status == 'up' && item.tunnelStatusB.status == 'up' ? true : false ) : false,
          });
          onData([...dataSource])
        })
        
      } else {
        Message.error({
          content: res.msg,
          duration: 1000
        })
      }
      onShowLoading(false)
    }).catch(e => {
      Message.error('Unknown Error')
      onShowLoading(false)
    })
    
  }

  const handleDelete = (e, id) => {
    const dialog = Dialog.confirm({
      title: 'Delete Tunnel',
      content: 'Are you sure to delete Tunnel?',
      messageProps:{
        type: 'warning'
      },
      footer: (
        <>
          <Button warning type="primary" onClick={
            () => {
              if(id) {
                delTunnels({
                 [`${id}`]: true
                }).then(res => {
                  if(res.code == 200) {
                    Message.success(res.msg)
                  } else {
                    Message.error(res.msg)
                  }
                  dialog.hide();
                  window.location.reload();
                }).catch(e=>{
                  console.log(e);
                  window.location.reload();
                })
              } else {
                if( sel.length > 0 ) {
                  let obj = {};
                  sel.forEach(item=>{
                    obj[item] = true;
                  })
                  delTunnels(obj).then(res => {
                    if(res.code == 200) {
                      Message.success(res.msg)
                    } else {
                      Message.error(res.msg)
                    }
                    dialog.hide();
                    window.location.reload()
                  }).catch(e=>{
                    console.log(e);
                    Message.error(res.msg)
                  })
                } else {
                  Message.notice('未选择设备')
                }
              }
            }
          }>
              Delete
          </Button>
          <Button style={{marginLeft: '10px'}} onClick={() => dialog.hide()}>
              Cancel
          </Button>
        </>
      )
    });
    
    
  }

  // table的列配置
const tableConfig = [
  {
    title: 'ID',
    dataIndex: 'id',
    sortable: true
  },
  {
    title: 'Device A',
    dataIndex: 'deviceA',
    sortable: true
  },
  {
    title: 'Interface A',
    dataIndex: 'interfaceA',
    sortable: true
  },
  {
    title: 'Device B',
    dataIndex: 'deviceB',
    sortable: true
  },
  {
    title: 'Interface B',
    dataIndex: 'interfaceB',
    sortable: true
  },
  {
    title: 'Path Label',
    dataIndex: 'pathlabel',
    sortable: true
  },
  {
    title: 'AVG Latency',
    dataIndex: 'rtt',
    sortable: true
  },
  {
    title: 'Drop Rate',
    dataIndex: 'drop_rate',
    sortable: true
  },
  {
    title: 'Status',
    dataIndex: 'status',
    sortable: false,
    content: (value, index, record) => {
      return (
        <Tag size="small" type="normal" color={record.status ? 'green' : 'red'}>
          {record.status ? 'Connected' : 'Not Connected'}
        </Tag>
      )
    }
  },
  {
    title: 'Actions',
    dataIndex: 'actions',
    sortable: false,
    content: (value, index, record) => {
      console.log('value', value)
      return (
        <Button className={`round-button`} type="primary" warning onClick={(e) => handleDelete(e, record.id)}>
          <CustomIcon type="icondelete" />
        </Button>
      )
    }
  },
];

  useEffect(() => {
    handleUpdate()
  }, [])
  // 表选择
  const onTableChange = (selectedRowKeys,records) => {
    onSel(selectedRowKeys);
    console.log('records', records)
  };

  const rowSelection = {
      onChange: onTableChange,
      getProps: (record) => {
          
      }
  };

  // 分页
  const onPageChange = currentPage => {
    onCurrentPage(currentPage)
  }

  let d = data.slice((currentPage-1)*PAGE_SIZE,currentPage*PAGE_SIZE)
  

  return (
    <WrapperPage path={props.location.pathname}>
      <Loading visible={showLoading}>
      <div className={styles['tunnels-content']}>
        <div className={styles['content-filter']}>
          <Button type="primary" className={`${styles['left']} round-button`} onClick={(e) => handleUpdate(e, '')}>
            <CustomIcon type="iconsync"/>
          </Button>
          {
            sel.length > 0 && (<Button warning type="primary" className={`${styles['right']}`} onClick={handleDelete}>
              Delete Tunnels
            </Button>)
          }
          
         </div>
         <div className={styles['content-display']}>
          <div className={styles['display-table']}>
            <Table
              rowSelection={rowSelection}
              dataSource={d}
            >
              {
                tableConfig.map((item,i) => {
                  return (
                    <Table.Column 
                      key={i} 
                      title={item.title} 
                      dataIndex={item.dataIndex} 
                      sortable={item.sortable}
                      cell={item.content} 
                    />
                  )
                })
              }
            </Table>
          </div>
          <div className={styles['display-pagination']}>
            <Pagination 
              onChange={onPageChange}
              total={data.length}
              pageSize={PAGE_SIZE}
              pageShowCount={5} 
            />
          </div>
         </div>
         
      </div>
    </Loading>
    </WrapperPage>
    
  );
};

export default Tunnels;
